package com.web.homework;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.web.DataSourceUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

@WebServlet("/work5")
//post请求 /work5?id=1&name=新名字
public class work5 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求编码
        request.setCharacterEncoding("UTF-8");
        // 设置响应内容类型和编码
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取学生ID和新的姓名
        String idStr = request.getParameter("id");
        String newName = request.getParameter("name");
        if (idStr == null || idStr.isEmpty() || newName == null || newName.isEmpty()) {
            response.getWriter().println("ID和姓名参数不能为空");
            return;
        }
        int id = Integer.parseInt(idStr);

        // 更新学生信息
        boolean success = updateStudentById(id, newName);

        // 打印结果到控制台
        if (success) {
            System.out.println("学生信息更新成功");
            response.getWriter().println("学生信息更新成功");
        } else {
            System.out.println("学生信息更新失败");
            response.getWriter().println("学生信息更新失败");
        }
    }

    // 通过ID更新学生信息的方法
    private boolean updateStudentById(int id, String newName) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        DataSource dataSource = null;

        Properties properties = new Properties();
        try {
            // 读配置文件
            properties.load(DataSourceUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            // 初始化数据源
            dataSource = DruidDataSourceFactory.createDataSource(properties);

            // 获取连接
            connection = dataSource.getConnection();
            // 创建预编译语句
            String sql = "UPDATE student SET name = ? WHERE id = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, newName);
            preparedStatement.setInt(2, id);
            // 执行更新
            int affectedRows = preparedStatement.executeUpdate();

            // 返回更新是否成功
            return affectedRows > 0;
        } catch (IOException | SQLException e) {
            throw new RuntimeException("初始化数据源失败: " + e.getMessage(), e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭资源
            try {
                if (preparedStatement != null) preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (connection != null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}